<template>
  <div class="simple-test">
    <h2>流式响应简单测试</h2>
    <div class="input-area">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </div>
    
    <div class="messages">
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message', msg.type]"
      >
        {{ msg.content }}
      </div>
    </div>
    
    <div class="debug-info">
      <h3>调试信息</h3>
      <pre>{{ debugInfo }}</pre>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SimpleTest',
  data() {
    return {
      inputMessage: '',
      isLoading: false,
      messages: [],
      debugInfo: '等待发送消息...'
    }
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const message = this.inputMessage.trim()
      this.inputMessage = ''
      this.isLoading = true
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: message
      })
      
      // 添加AI消息占位符
      const aiMessageIndex = this.messages.length
      this.messages.push({
        type: 'assistant',
        content: ''
      })
      
      this.debugInfo = `发送消息: ${message}\n等待响应...`
      
      try {
        // 直接使用fetch进行测试
        const response = await fetch('/dev-api/api/ai/chat/send/stream', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream'
          },
          body: JSON.stringify({
            message: message,
            userId: 'test-user',
            conversationId: null,
            createNewConversation: true
          })
        })
        
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }
        
        this.debugInfo += `\n连接成功，开始接收数据...`
        
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        
        while (true) {
          const { done, value } = await reader.read()
          
          if (done) {
            this.debugInfo += `\n流式响应完成`
            break
          }
          
          const chunk = decoder.decode(value, { stream: true })
          this.debugInfo += `\n收到数据块: ${chunk}`
          
          const lines = chunk.split('\n')
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const payload = line.substring(6)
              this.debugInfo += `\n处理payload: ${payload}`
              
              if (payload === '[DONE]') {
                this.debugInfo += `\n流式响应完成`
                break
              } else {
                try {
                  const parsed = JSON.parse(payload)
                  if (parsed.content) {
                    this.debugInfo += `\n收到内容: ${parsed.content}`
                    this.messages[aiMessageIndex].content += parsed.content
                  } else if (parsed.conversationId) {
                    this.debugInfo += `\n收到会话ID: ${parsed.conversationId}`
                  }
                } catch (e) {
                  this.debugInfo += `\nJSON解析失败: ${payload}`
                }
              }
            }
          }
        }
        
      } catch (error) {
        this.debugInfo += `\n错误: ${error.message}`
        this.messages[aiMessageIndex].content = `错误: ${error.message}`
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
.simple-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.input-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.input-area input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.input-area button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.messages {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  height: 300px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message {
  margin: 5px 0;
  padding: 8px;
  border-radius: 4px;
}

.message.user {
  background: #e3f2fd;
  text-align: right;
}

.message.assistant {
  background: #f1f8e9;
}

.debug-info {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background: #f8f9fa;
}

.debug-info pre {
  white-space: pre-wrap;
  font-size: 12px;
  margin: 0;
}
</style>
